import { IBaseContentPage } from '@lib/IBaseIssuePage';
import { SSLib } from '@lib/SSLib';
import * as $ from 'jquery';

export class RepositoryEeditorPage implements IBaseContentPage {
    constructor() {
        ;
    }

    public IsMatch(url: string) {
        return /repository\/editor/.test(url);
    }

    public Execute() {
        init();
    }
}

let curRap2Data: rap2Data = null;

function init() {
    let $btnCopy = $('<button class="btn btn-success">拷贝单项</button>');
    let $btnCopySuper = $('<button class="btn btn-primary">拷贝单组</button>');
    let $btnCopySuper2 = $('<button class="btn btn-danger">拷贝全部</button>');

    var $groupContainer = $('.MuiToolbar-root .jss16');
    $groupContainer.append($btnCopy);
    $groupContainer.append($btnCopySuper);
    $groupContainer.append($btnCopySuper2);

    $btnCopy.click(()=>{
        var curLocalurl = location.href;
        var title = $('.InterfaceSummary .title').text();
        var url = $('.InterfaceSummary a').text();

        let text = `
* ${title}  
  ${url} [rap2文档](${curLocalurl})`;

        SSLib.CopyToClipboard(text);
    });

    SSLib.gGet(`http://rap2.dev.ofpanda:38080/repository/get?id=${SSLib.GetQueryValue('id')}&excludeProperty=true`, json => {
        curRap2Data = json.data as rap2Data;
    });

    $btnCopySuper.click(() => {
        if (!curRap2Data) {
            alert("拷贝失败，未请求到数据");
            return false;
        }

        var curMod = parseInt(SSLib.GetQueryValue('mod'));
        
        var text = getModuleText(curMod);

        SSLib.CopyToClipboard(text);
    });

    $btnCopySuper2.click(() => {
        var text = ``;
        curRap2Data.modules.forEach(a => {
            text += getModuleText(a.id) + ' \r\n\r\n';
        });

        SSLib.CopyToClipboard(text);
    });
}

function getModuleText(curMod: number) {
    var module = curRap2Data.modules.find(a => a.id === curMod);
    let urlBase = location.href.substr(0, location.href.indexOf('?'));
    var text = `#### ${module.name}`;
    module.interfaces.forEach(a => {

        text += `

* ${a.name}  
${a.url} [rap2文档](${urlBase}?id=${a.repositoryId}&mod=${a.moduleId}&itf=${a.id})`;
    });

    return text;
}

class rap2Data {
    public modules: modules[];
}

class modules {
    public id: number;
    public name: string;
    public interfaces: interfaces[];
}

class interfaces {
    public id: number;
    public moduleId: number;
    public repositoryId: number;
    public name: string;
    public url: string;
}